import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:flutter/cupertino.dart';
import 'package:x5_webview/x5_webview.dart';
import 'package:webview_flutter/webview_flutter.dart';

class DemoWebViewPage extends StatefulWidget {
  final url;

  DemoWebViewPage(this.url);

  @override
  _DemoWebViewPageState createState() => _DemoWebViewPageState(url);
}

class _DemoWebViewPageState extends State<DemoWebViewPage> {
  X5WebViewController _controller;
  final url;

  _DemoWebViewPageState(this.url);

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Scaffold(
          // appBar: AppBar(
          //   title: Text("X5WebView示例"),
          //   actions: <Widget>[
          //     IconButton(
          //         icon: Icon(Icons.close),
          //         onPressed: () {
          //           Navigator.pop(context);
          //         })
          //   ],
          // ),
          body:
          ConstrainedBox(
            constraints: BoxConstraints.expand(),
            child: Stack(
              alignment:Alignment.center , //指定未定位或部分定位widget的对齐方式
              children: <Widget>[
                Column(children: <Widget>[
                  Expanded(
                      child: defaultTargetPlatform == TargetPlatform.android
                          ? X5WebView(
                        url: url,
                        javaScriptEnabled: true,
                        header: {"TestHeader": "测试", "MSG": "在？在干嘛？吃饭了没？"},
                        userAgentString: "aaaa",
                        javascriptChannels: JavascriptChannels(
                            [/*"X5Web", "Toast",*/"mpService"], (name, data) {

                              print(name);
                              var _data = jsonDecode(data);
                              print(_data['func']);
                              print(_data);
                              switch(_data['func']){
                                case 'navigateTo':
                                  mpNavigateTo(context, _data['data']);
                                  break;
                                case 'navigateBack':
                                  mpNavigateBack(context,_data['data']);
                                  break;
                                case 'redirectTo':
                                  mpRedirectTo(context,_data['data']);
                                  break;
                                case 'reLaunch':
                                  mpReLaunch(context,_data['data']);
                                  break;
                              }


                          //   switch (name) {
                          //     case "mpService":
                          //       showDialog(
                          //           context: context,
                          //           builder: (context) {
                          //             return AlertDialog(
                          //               title: Text("mpService 获取到的字符串为："),
                          //               content: Text(data),
                          //             );
                          //           });
                          //       break;
                          //     case "X5Web":
                          //       showDialog(
                          //           context: context,
                          //           builder: (context) {
                          //             return AlertDialog(
                          //               title: Text("获取到的字符串为："),
                          //               content: Text(data),
                          //             );
                          //           });
                          //       break;
                          //     case "Toast":
                          //       print(data);
                          //       break;
                          //   }
                          }
                        ),
                        onWebViewCreated: (control) {
                          _controller = control;
                        },
                        onPageFinished: () async {
                          var url = await _controller.currentUrl();
                          print(url);
                        },
                        onProgressChanged: (progress) {
                          print("webview加载进度------$progress%");
                        },
                        onUrlLoading: (_url) {
                          print(_url);
                          showDialog(
                              context: context,
                              builder: (_) {
                                return AlertDialog(
                                  content: Text("url==$_url"),
                                  actions: [
                                    FlatButton(
                                      child: Text("我知道了"),
                                      onPressed: () {
                                        Navigator.pop(context);
                                      },
                                    )
                                  ],
                                );
                              });
                        },
                      )
                          :
                      //可替换为其他已实现ios webview,此处使用webview_flutter
                      WebView(
                        initialUrl: url,
                        javascriptMode: JavascriptMode.unrestricted,
                        javascriptChannels: [
                          JavascriptChannel(
                              name: "X5Web",
                              onMessageReceived: (msg) {
                                print(msg);
                              })
                        ].toSet(),
                          onWebViewCreated: (control) {
  //                _otherController = control;
  //                var body = _otherController
  //                    .evaluateJavascript('document.body.innerHTML');
  //                print(body);
                        },
                      )),
                  //调用JS
                  // RaisedButton(
                  //   onPressed: () {
                  //     _controller.evaluateJavascript(
                  //         'document.getElementById("input").value="flutter调用js成功！"');
                  //   },
                  //   child: Text("flutter调用js(更改文字)"),
                  // )
                ]),
                //右上角浮动按钮
                Positioned(
                  top: 35.0,
                  right:18.0,
                  height: 35.0,
                  child: DecoratedBox(
                      decoration: BoxDecoration(
                          color: Color.fromARGB(48, 0, 0, 0),
                          borderRadius: BorderRadius.circular(16), //圆角
                      ),
                      child: Padding(padding: EdgeInsets.symmetric(horizontal: 0, vertical: 0),
                        child: Row(
                          children: [
                            //更多
                            IconButton(
                              padding: EdgeInsets.all(0),
                              icon: Icon(
                                Icons.more_horiz_outlined,
                                color: Colors.white,
                              ),
                              onPressed: ()=>{
                                closeMP(context)
                              },
                            ),
                            //关闭按钮
                            IconButton(
                              padding: EdgeInsets.all(0),
                              icon: Icon(
                                Icons.close_outlined,
                                color:Colors.white
                              ),
                              onPressed: ()=>{
                                closeMP(context)
                              },
                            )
                          ],
                        )
                      )
                  ),
                )
              ],
            ),
          )
        ),
        onWillPop: () async {
          var canGoBack = await _controller.canGoBack();
          if (canGoBack) {
            _controller.goBack();
            return false;
          } else {
            return true;
          }
        });
  }
}
//加载html 公共方法
loadHtml(urlPath) async {
  //html
  var fileHtmlContents = await rootBundle.loadString("assets/mptest/${urlPath}.html",cache: false);
  //js桥接器
  var mpJsContent = await rootBundle.loadString('assets/mp.js',cache:false);
  var url = Uri.dataFromString("${fileHtmlContents}<script>${mpJsContent}<\/script>",
      mimeType: 'text/html',
      encoding: Encoding.getByName('utf-8'))
      .toString();
  return url;
}

//关闭小程序
closeMP(ctx) {
  // Navigator.pop(ctx);
  Navigator.of(ctx).pushNamedAndRemoveUntil("/home", (Route<dynamic> route) => false);
}

/*
* 路由
* */
//跳转
mpNavigateTo(ctx, data) async {
  var urlPath = data['url'];
  var url = await loadHtml(urlPath);
  Navigator.of(ctx)
      .push(CupertinoPageRoute(builder: (BuildContext context) {
    return DemoWebViewPage(url);
  }));
}
//返回上一页
mpNavigateBack(ctx,data) async {
  var delta = 1;
  if(data!=null && data['delta']!=null){
    print(data['delta']);
    delta = data['delta'];
  }
  for(var i=0;i<delta;i++){
    Navigator.of(ctx).pop();
  }
}
//关闭当前页面，跳转到应用内的某个页面
mpRedirectTo(ctx,data) async {
  var urlPath = data['url'];
  var url = await loadHtml(urlPath);
  Navigator.of(ctx)
      .pushReplacement(CupertinoPageRoute(builder: (BuildContext context) {
    return DemoWebViewPage(url);
  }));
}
//
mpReLaunch(ctx,data) async {
  var urlPath = data['url'];
  var url = await loadHtml(urlPath);
  closeMP(ctx);
  Navigator.of(ctx)
      .push(CupertinoPageRoute(builder: (BuildContext context) {
    return DemoWebViewPage(url);
  }));
}